package com.chentong.servlet;

import com.chentong.utils.ApplicationContext;
import com.chentong.utils.ClassNameUtils;;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

public class DispatcherServlet extends HttpServlet {
    private Map<String, Object> iocMap;
    private Map<String, Method> handlerMap;

    @Override
    public void init(ServletConfig config) throws ServletException {
        String xmlPath = config.getInitParameter("applicationContextConfig");
        ApplicationContext applicationContext = new ApplicationContext();
        try {
            applicationContext.init(xmlPath);
            iocMap = applicationContext.getApplicationContext();
            handlerMap = applicationContext.getRegisteredHandler();
            System.out.println("IOC container is:");
            System.out.println(iocMap);
            System.out.println();
            System.out.println("URL mapping is:");
            System.out.println(handlerMap);
            System.out.println();
            System.out.println("Init successfully");
            System.out.println("Chen Tong provides technical support");
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        Method method = handlerMap.get(uri);
        Class<?> declaringClass = method.getDeclaringClass();
        String simpleName = ClassNameUtils.humpNaming(declaringClass.getSimpleName());
        Object object = iocMap.get(simpleName);
        try {
            method.invoke(object, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
